package com.zlb.app.common.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Desc 接口访问切面, 打印方法名及参数
 * @Author zWX1367238
 * @Date 2024-08-27 10:05:22
 **/
@Aspect
@Component
public class ControllerMethodAspect {

    // 应用上下文
    @Autowired
    private ApplicationContext applicationContext;

    // 切点
    @Pointcut("execution(public * com.zlb.app.modules.*.controller.*.*(..))*")
    public void paramsLogPointcut() {
    }

    @Before(value = "paramsLogPointcut()")
    public void before(JoinPoint joinPoint) {
        try {
            Object[] args = joinPoint.getArgs();
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            String methodName = method.getName();
            Api api = (Api) signature.getDeclaringType().getAnnotation(Api.class);
            String apiStr = ObjectUtil.isNotEmpty(api) ? "请求模块:" + StrUtil.join(",", api.tags()) + "," : "";
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            String str = ObjectUtil.isNotEmpty(apiOperation) ? "(" + apiOperation.value() + ")" : "";
            StaticLog.info("{}请求方法:{}{},入参:{}", apiStr, methodName, str, JSONUtil.toJsonStr(args));
        } catch (Exception e) {
            StaticLog.error("控制层参数打印切面异常:{}", e.getMessage());
        }
    }

}
